package cn.huaqingcheng.tianshu.web.config;

import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 时间监视器过滤器
 */
@Slf4j
@ToString
@Component
@NoArgsConstructor
@EqualsAndHashCode
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(displayName = "时间监视器过滤器", description = "时间监视器过滤器")
public class TimeMonitorFilter implements Filter, Ordered {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        try {
            chain.doFilter(request, response);
        } finally {
            long end = System.currentTimeMillis();
            if (log.isTraceEnabled()) {
                log.trace("耗时: {} ms", end - start);
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
